/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * selPessoa.java
 *
 * Created on 21/11/2009, 15:25:03
 */

package JPaneis;

import Data.Cliente;
import Data.Funcionario;
import Data.Pessoa;
import java.awt.Component;
import java.awt.GridLayout;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;

/**
 *
 * @author Administrator
 */
public class selPessoa extends javax.swing.JFrame {

    private static ArrayList<Pessoa> funcList;
    private static final String[] campos_func = {"CPF" ,"NOME", "SOBRENOME", "APELIDO"};
    private static final String[] campos_cli = {"NUMERO_DO_PESCADOR","NOME", "SOBRENOME", "APELIDO", "CPF"};
    private static String[] campos;
    private JPanel retMcf = null;

    /** Creates new form selPessoa */
    public selPessoa() {
        initComponents();
    }

    public selPessoa(ArrayList funcionarios, JPanel mcf) {
        initComponents();
        retMcf = mcf;
        if (funcionarios.get(0) instanceof Funcionario)
            campos = campos_func;
        else if (funcionarios.get(0) instanceof Cliente)
            campos = campos_cli;
        funcList = funcionarios;
        this.setLocationRelativeTo(mcf);
        this.setVisible(true);
        refreshList();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        selList = new javax.swing.JList();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        selList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        selList.setCellRenderer(null);
        selList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                selListMouseClicked(evt);
            }
        });
        selList.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                selListKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(selList);

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/salvar.png"))); // NOI18N
        jButton1.setText("Selecionar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/cancelar.png"))); // NOI18N
        jButton2.setText("Cancelar");
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton2MouseClicked(evt);
            }
        });
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setText("Selecione  para Editarr:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 700, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 477, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                        .addComponent(jButton2)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 164, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void selListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_selListMouseClicked

        if(evt.getClickCount() == 2){
            setSelectedElement();
        }
}//GEN-LAST:event_selListMouseClicked

    private void selListKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_selListKeyPressed
        if(evt.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER){
            setSelectedElement();
        }
}//GEN-LAST:event_selListKeyPressed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        setSelectedElement();
}//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked
        // TODO add your handling code here:
}//GEN-LAST:event_jButton2MouseClicked

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.setVisible(false);
        retMcf.setVisible(true);
}//GEN-LAST:event_jButton2ActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new selPessoa().setVisible(true);
            }
        });
    }

    private void setSelectedElement(){
        int selectedIndex = selList.getSelectedIndex();
        Pessoa pessoa = funcList.get(selectedIndex);
        ((panelTools)retMcf).setScreen(pessoa);
        this.setVisible(false);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList selList;
    // End of variables declaration//GEN-END:variables

    void refreshList() {

          String[][] dados = getListData();
          //set list for JList
          selList.setListData(dados);
          //create Renderer and dislpay
          System.out.println("colunas: " + dados[0].length);
          selList.setCellRenderer((ListCellRenderer) new MyCellRenderer(dados[0].length));
    }

    private String[][] getListData(){
        String[][] dados = null;
        //List<Map<String,?>> lista = null;
        try {
            //lista = (List<Map<String,?>>) HashPersistence.getInstance().doRawSQL("SELECT " + campos + " FROM SERVICO_PESCA");
        } catch (Exception ex) {
            //Logger.getLogger(MenuCadastrarEditarServicoPesca.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }
        System.out.flush();
        int line = 0;
        int col = 0 ;

        for(Pessoa func : funcList){
            if (dados == null){
                dados = new String[funcList.size()][campos.length];
            }
           // System.out.println(m);
            for(String key : campos){
                System.out.println("}}" + key + ":" + func.getData(key) + ":" + line + ":" + col);
                Object campo = func.getData(key);
                dados[line][col++] = campo != null ? campo.toString() : "";
            }
            line++;
            col=0;
        }

        return dados;
    }

        static class MyCellRenderer extends JPanel implements ListCellRenderer {

        ArrayList<JLabel> labels = new ArrayList();
        JLabel left, middle, right;
        int cols;

        MyCellRenderer(int cols) {
            this.cols = cols;
            setLayout(new GridLayout(1, cols));
            for (int i=0; i < cols;i++){
                JLabel label = new JLabel();
                label.setOpaque(true);
                add(label);
                labels.add(label);
            }
        }

        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            int i = 0;
            for (JLabel jl : labels) {
                jl.setText(((String[])value)[i++]) ;
                if (isSelected) {
                    jl.setBackground(list.getSelectionBackground());
                    jl.setForeground(list.getSelectionForeground());
                } else {
                    jl.setBackground(list.getBackground());
                    jl.setForeground(list.getForeground());
                }
            }

            setEnabled(list.isEnabled());
            setFont(list.getFont());
            return this;
        }
    }

}
